package itbour.onetouchshow.activity.version1_2;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.google.gson.Gson;
import com.lsjr.utils.NetUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.PictureSelectionConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.umeng.analytics.MobclickAgent;
import com.utils.permission.Permission;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.regex.Matcher;

import butterknife.BindView;
import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.version1_3.VideoCoverActivity;
import itbour.onetouchshow.activity.video.videobg.VideobgDialgActivity;
import itbour.onetouchshow.activity.video.videopreview.VideoPreviewActivity;
import itbour.onetouchshow.activity.web.CommWebActivity;
import itbour.onetouchshow.activity.web.CreateOrderActivity;
import itbour.onetouchshow.base.IntentCode;
import itbour.onetouchshow.bean.CoverInfo;
import itbour.onetouchshow.bean.VideoPreviewBean;
import itbour.onetouchshow.bean.user.UserMakeTag;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.constants.platform.WorkPlatform;
import itbour.onetouchshow.listener.EdittextListener;
import itbour.onetouchshow.listener.PermissionListener;
import itbour.onetouchshow.listener.SoftKeyBoardListener;
import itbour.onetouchshow.utils.ImageLoader;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.OnMultiClickUtils;
import itbour.onetouchshow.utils.ShieldEmoji;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.ThirdAppInstall;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.video.EditPlayVideoFrames;
import itbour.onetouchshow.widget.LineEditText;
import itbour.onetouchshow.widget.StartThirdAppDialog;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */
@SuppressLint("ValidFragment")
public class V1_2_VideoPreviewActivity extends VideoPreviewActivity implements View.OnClickListener {

    @BindView(R.id.id_ly_edit_content)
    protected LinearLayout editContent;
    @BindView(R.id.id_ly_edit_bg)
    protected LinearLayout editBg;
    @BindView(R.id.id_ly_del_bg)
    protected LinearLayout delBg;
    @BindView(R.id.iv_left_bar)
    protected ImageView igClose;
    /*背景图片容器*/
    @BindView(R.id.id_prv_ry)
    protected RelativeLayout idPrvBgRy;
    @BindView(R.id.id_tv_save_share)
    protected TextView tvSaveShare;
    @BindView(R.id.id_tv_save_to_local)
    protected TextView tvSaveToLocal;
    @BindView(R.id.tv_share_to_other)
    protected TextView tvShareToOther;
    @BindView(R.id.ll_download_share_container)
    protected LinearLayout llDownloadShareContainer;

    @BindView(R.id.id_ig_chage_bg)
    protected ImageView imageViewbg;
    @BindView(R.id.id_ed_tv)
    protected TextView edTvbg;
    //作品状态
    @BindView(R.id.id_tv_product_tag)
    protected TextView tvProductTag;
    //名称
    @BindView(R.id.up_edit)
    protected LineEditText up_product_edit;
    @BindView(R.id.id_ly_cover)
    protected RelativeLayout lyCover;
    @BindView(R.id.id_ig_more)
    protected ImageView id_ig_more;
    @BindView(R.id.id_tv_cover_tag)
    protected TextView id_tv_cover_tag;
    @BindView(R.id.ig_video_rv)
    protected ImageView ig_video_rv;
    @BindView(R.id.tv_cover_settag)
    protected TextView tv_cover_settag;
    /*是否有背景*/
    protected boolean isHaveBg;
    /*
  * 避免没背景到有背景位置有误差  隐藏封面-50
  * */
    protected int isCleanTopMargin; /*= UIUtils.dp2px(130 + 20 - 50 - 20 - 15)*/
    protected boolean isShowCoverView = false;
    protected boolean ishaveCover = false;
    @BindView(R.id.id_root_ry)
    RelativeLayout id_root_ry;
    //NewComplexDialogFrag complexDialogFrag;
    /*完成*/
    @BindView(R.id.tv_right_bar)
    TextView tvOver;
    //封面
    @BindView(R.id.id_ly_edit_cover)
    LinearLayout id_ly_edit_cover;
    /**
     * 点击背景选择之后也是此操作
     * <p>
     * 点击切换背景先设置背景
     * <p>
     * 在获取作品预览
     * <p>
     * 设置背景后重新获取预览数据
     */
    String cover;
    /**
     * 用户操作区分
     */
    private UserMakeTag userMakeTag = UserMakeTag.UPDATE;

    public static Boolean hideInputMethod(Context context, View v) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            return imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
        return false;
    }

    public static boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            v.getLocationInWindow(leftTop);
            int left = leftTop[0], top = leftTop[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_videopreview1_2;
    }

    public UserMakeTag getUserMakeTag() {
        return userMakeTag;
    }

    public void setUserMakeTag(UserMakeTag userMakeTag) {
        this.userMakeTag = userMakeTag;
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        super.afterCreate(savedInstanceState);
        initOnClickListener();
    }

    @Override
    protected void initView() {
        super.initView();
        getToolBarView().setVisibility(View.GONE);
        //暂时隐藏封面入口
        if (isShowCoverView) {
            isCleanTopMargin = UIUtils.dp2px(130 + 20);
        } else {
            lyCover.setVisibility(View.GONE);
            isCleanTopMargin = UIUtils.dp2px(130 + 20 - 50 - 20 - 15);
        }
        //lyCover.setVisibility(View.GONE);
        showEdittextSetting();

    }

    public void initOnClickListener() {
        editBg.setOnClickListener(this);
        delBg.setOnClickListener(this);
        igClose.setImageResource(R.mipmap.return_icon);
        igClose.setOnClickListener(this);
        tvProductTag.setOnClickListener(this);
        tvSaveShare.setOnClickListener(this);
        tvSaveToLocal.setOnClickListener(this);
        idLyuserMake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setUserMakeTag(UserMakeTag.DOWNLOAD);
                saveAndShare();
            }
        });

        // tvOver.setOnClickListener(this);
        if (subType != null && subType.equals(WorkPlatform.W0RK)) {
            //个任务中心跳转逻辑
            tvOver.setText("修改");
            up_product_edit.setEnabled(false);
            up_product_edit.setBackground(null);
            up_product_edit.onDrawClean();
        } else {
            tvOver.setText("完成");
        }

        tvOver.setOnClickListener(this);

        up_product_edit.setFilters(new InputFilter[]{/*new InputFilter.LengthFilter(value.getMax()), */new InputFilter() {
            @Override
            public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
                Matcher matcher = ShieldEmoji.isEmoji().matcher(charSequence);
                if (matcher.find()) {
                    return "";
                }
                return null;
            }
        }});
        // up_product_edit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10), filter});
        //限制输入
        EdittextListener edittextListener = new EdittextListener(up_product_edit, AppConst.editTextMaxLength) {
            @Override
            public void afterTextChanged(Editable editable) {
                super.afterTextChanged(editable);
            }
        };
        up_product_edit.addTextChangedListener(edittextListener);
        id_ly_edit_cover.setOnClickListener(this);
        id_ly_edit_cover.setVisibility(View.GONE);
        lyCover.setOnClickListener(this);

    }

    /**
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            /**背景编辑**/
            case R.id.id_ly_edit_bg:
                if (OnMultiClickUtils.isFastClick()) {
                    if (NetUtils.isConnected(getApplication())) {

                        if (videoPreviewBean.getWatermark() == 1) {
                            //ActivityUtils.popAllActivityUntillOne(MakeActivity.class);
                            if (isHaveBg) {
                                gotoCommoninchingVideoBgActivity();
                            } else {
                                showBgDialog();
                            }
                        } else {
                            //已经去水印
                            setUserMakeTag(UserMakeTag.SETBG);
                            showUpdateWorkDialog();
                        }
                    } else {
                        T_.showCustomToast("请检查网络");
                    }
                }
                break;
            /**报名表单**/
            case R.id.id_ly_del_bg:
                if (OnMultiClickUtils.isFastClick()) {
                    if (NetUtils.isConnected(getApplication())) {
                        // mPresenter.deleteVideoBg(videoPreviewBean.getId() + "");
                        //添加表格
                        Bundle bundle = new Bundle();
                        bundle.putString(AppConst.WEBTYPE, AppConst.TYPE_ADDFORM);
                        bundle.putString(AppConst.DOCID, videoPreviewBean.getId() + "");
                        Intent intent = new Intent(V1_2_VideoPreviewActivity.this, CommWebActivity.class);
                        //  openActivity(CommWebActivity.class, bundle);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        //startActivityForResult(intent, 200);
                    } else {
                        T_.showCustomToast("请检查网络");
                    }

                }
                break;
            /**左边返回按钮**/
            case R.id.iv_left_bar:
                jugleQuit();
                break;
            /**作品状态*/
            case R.id.id_tv_product_tag:
                if (NetUtils.isConnected(getApplication())) {
                    if (videoPreviewBean.getWatermark() == 1 && videoPreviewBean.getWatermarkPay() == 1) {
                        showProgressDialogWithText("正在努力去水印");
                        mPresenter.removeWatermark(videoPreviewBean.getId() + "");
                    } else {
                        // showRemoveWaterDialog();
                        Bundle bundle = new Bundle();
                        bundle.putString("docId", videoPreviewBean.getId() + "");
                        openActivity(CreateOrderActivity.class, bundle);
                    }
                } else {
                    T_.showCustomToast("请检查网络");
                }
                break;
            /**完成或者修改**/
            case R.id.tv_right_bar:
            case R.id.tv_right:
                if (!OnMultiClickUtils.isFastDoubleClick(R.id.tv_right_bar)) {
                    if (subType != null && subType.equals(WorkPlatform.W0RK)) {
                        if (videoPreviewBean.getWatermark() == 1) {
                            mPresenter.getDocString(videoPreviewBean.getId() + "");
                        } else {
                            //如果已经去水印  重新拷贝生成
                            setUserMakeTag(UserMakeTag.UPDATE);
                            showUpdateWorkDialog();
                        }
                    } else {
                        sendRemoveThreeLogic();
                    }
                }
                break;
            /**作品名称**/
            case R.id.up_edit:
                break;
            case R.id.id_ly_edit_cover:
                gotoSelectType();
                break;
            /**封面入口**/
            case R.id.id_ly_cover:
                if (videoPreviewBean.getWatermark() == 1) {
                    gotoCoverActivity();
                } else {
                    //如果已经去水印
                    //ActivityUtils.popAllActivityUntillOne(MakeActivity.class);
                    setUserMakeTag(UserMakeTag.SETCOVER);
                    showUpdateWorkDialog();
                }
                break;
            case R.id.id_tv_save_share:
            case R.id.id_tv_save_to_local:
                setUserMakeTag(UserMakeTag.DOWNLOAD);
                saveAndShare();
                break;
        }
    }

    protected void gotoCoverActivity() {
        Intent intent = new Intent(V1_2_VideoPreviewActivity.this, VideoCoverActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(AppConst.VIDEOURL, videoBean.getVideoUrl());
        bundle.putString("docId", videoPreviewBean.getId() + "");
        bundle.putDouble(AppConst.VIDEOW, videoBean.getW());
        bundle.putDouble(AppConst.VIDEOH, videoBean.getH());
        bundle.putBoolean(AppConst.ISHAVECOVER, ishaveCover);
        bundle.putBoolean("islocalhost", false);
        bundle.putDouble("duration", videoBean.getDuration() * 1000);
        if (ishaveCover) {
            bundle.putDouble("coverDuration", videoBean.getCoverInfo().getCoverDuration());
        }
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        cleanEditTextFocus();
    }

    public void cleanEditTextFocus() {
        id_root_ry.setFocusable(true);
        id_root_ry.setFocusableInTouchMode(true);
        id_root_ry.requestFocus();
        up_product_edit.clearFocus();
    }

    @SuppressLint("ValidFragment")
    public void showUpdateWorkDialog() {
        String context;
        if (getUserMakeTag().equals(UserMakeTag.SETCOVER)) {
            context = "你已为此作品去水印，请重新生成作品后设置封面";
            showAlertDialog(context);
        } else if (getUserMakeTag().equals(UserMakeTag.SETBG)) {
            context = "你已为此作品去水印，请重新生成作品后设置背景";
            showAlertDialog(context);
        } else {
            // context = "去水印后,修改作品将生成带水印新作品，去水印作品仍会保留";
            mPresenter.getCopyDocStringAndNew(videoPreviewBean.getId() + "");
        }

    }

    public void showAlertDialog(String context) {


        new OneToucDialog.Builder(this)
                .content(context)
                .positiveText("重新生成").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                mPresenter.getCopyDocStringAndNew(videoPreviewBean.getId() + "");
                Log.e("TAH", "点击确定");
            }
        })
                .negativeText("取消").onNegative(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false).setmWidth(AppConst.APP_DIALOG_WIDTH)
                .show();
    }

    public void saveAndShare() {
        requestPermission(new PermissionListener() {
            @Override
            public void onGranted() {
                T_.showToastReal("下载");
                showProgressDialogWithText("正在下载...");
                mPresenter.getDownVideoUrl(videoPreviewBean.getId() + "");
            }

            @Override
            public void onDenied(List<String> list) {
                T_.showToastReal("没有权限");
            }
        }, Permission.Group.STORAGE);
    }

    @Override
    public void downLoadVideoSuccess(String string) {
        dismissProgressDialog();
        OneToucDialog show = new OneToucDialog.Builder(this)
                .content("已成功下载到本地")
                .positiveText("确定").onPositive(new OneToucDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(OneToucDialog dialog, DialogAction which) {
                        Log.e("TAH", "点击确定");
                    }
                }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false).setmWidth(AppConst.APP_DIALOG_WIDTH)
                .show();

        if (ThirdAppInstall.isAvailableOne(getApplicationContext())) {
            StartThirdAppDialog.getInstance().onShow(V1_2_VideoPreviewActivity.this);
        }

    }

    protected void gotoCommoninchingVideoBgActivity() {
        Bundle bundle = new Bundle();
        bundle.putInt(IntentCode.INCHING_TYPE, IntentCode.SUB_TYPE_PRODUCE);
        bundle.putInt(IntentCode.TAG, IntentCode.INTENT_VERTICAL_VIDEP);
        bundle.putInt(AppConst.BGID, Integer.valueOf(videoPreviewBean.getId()));
        bundle.putString(AppConst.DOCID, videoPreviewBean.getId() + "");
        bundle.putString(WorkPlatform.TYPE, subType);
        openActivity(CommoninchingVideoBgActivity.class, bundle);
    }

    @Override
    public void loadDocPreviewSuccess(String result) {
        L_.e(result);
        dismissProgressDialog();
        videoPreviewBean = new Gson().fromJson(result, VideoPreviewBean.class);
        //作品名称
        up_product_edit.setText(videoPreviewBean.getDocNm());
        up_product_edit.setSingleLine();


        bgInfo = videoPreviewBean.getBgInfo();
        mbgColumn = bgInfo.getColumn();
        mbgData = bgInfo.getList();
        videoBean = videoPreviewBean.getVideo();

        VideoPreviewBean.BgInfoBean.CurrentBgBean currentBg = bgInfo.getCurrentBg();
        //没有背景的
        if (currentBg == null) {
            isHaveBg = false;
            bgUrl = null;
            cleanBg();
        } else {
            isHaveBg = true;
            videoFrame = bgInfo.getCurrentBg().getVideoFrame();
            bgUrl = bgInfo.getCurrentBg().getImage().getThumbs().get(0);
            //有视频尺寸才设置背景
            if (videoFrame != null) {
                showRealSizeView();
            }
        }
        CoverInfo coverInfo = videoBean.getCoverInfo();
        /*封面*/
        if (coverInfo == null) {
            ig_video_rv.setVisibility(View.GONE);
            tv_cover_settag.setVisibility(View.VISIBLE);
            tv_cover_settag.setText("未设置");
            ishaveCover = false;
        } else {
            cover = videoBean.getCoverInfo().getCover();
            ishaveCover = true;
            if (!TextUtils.isEmpty(cover)) {
                ImageLoader.getInstance().showImage(this, cover, ig_video_rv);
                ImageLoader.getInstance().showImage(V1_2_VideoPreviewActivity.this, cover, controller.imageView());
            }
            tv_cover_settag.setVisibility(View.GONE);
            ig_video_rv.setVisibility(View.VISIBLE);
        }

        menu.setVisibility(View.GONE);
        ryRecommended.setVisibility(View.GONE);
        contentLayout.setVisibility(View.VISIBLE);
        waterStatus();


        customVideoPlay.releasePlayer();
        customVideoPlay.start();
        onChageUrlStartPlay(videoPreviewBean.getVideo().getVideoUrl(), videoPreviewBean.getDocNm());
        customVideoPlay.seekTo(10);

    }

    /*去水印完成*/
    @Override
    public void removeWaterLoadDocPreview(String result) {
    }

    public void showEdittextSetting() {
        //rwb：取消EditText焦点，并且隐藏输入法。
        SoftKeyBoardListener.setListener(V1_2_VideoPreviewActivity.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
            }

            @Override
            public void keyBoardHide(int height) {
                //L_.i("键盘隐藏 高度" + height);
                if (!TextUtils.isEmpty(up_product_edit.getText().toString()) && up_product_edit.getText().length() > 0) {
                    // mPresenter.deleteVideoBg(up_product_edit.getText().toString());
                    mPresenter.doReNameWork(videoPreviewBean.getId() + "", up_product_edit.getText().toString());
                }
                cleanEditTextFocus();
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                if (hideInputMethod(this, v)) {
                    cleanEditTextFocus();
                    return true; //隐藏键盘时，其他控件不响应点击事件==》注释则不拦截点击事件
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void showRealSizeView() {
        VideoPreviewBean.BgInfoBean.CurrentBgBean.ImageBean image = videoPreviewBean.getBgInfo().getCurrentBg().getImage();
        int w = (int) image.getW();
        int h = (int) image.getH();
        int x = (int) videoFrame.getX();
        int y = (int) Math.ceil(videoFrame.getY());
        int videoH = (int) videoFrame.getH();
        int[] whd = UIUtils.WHD();
        int visableW = whd[0];
        float scale = w * 1.0f / visableW;

        RelativeLayout.LayoutParams imgLp = (RelativeLayout.LayoutParams) idPrvBg.getLayoutParams();
        h = (int) (visableW * h * 1.0f / w);
        imgLp.width = visableW;
        imgLp.height = h;
        idPrvBg.setLayoutParams(imgLp);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) idVideoRy.getLayoutParams();
        y = (int) Math.ceil(y * 1.0f / scale);
        x = (int) Math.ceil(x * 1.0f / scale);
        videoH = (int) (videoH * 1.0f / scale);
        lp.leftMargin = x;
        lp.topMargin = y + isCleanTopMargin;
        lp.height = videoH;
        int videoW = (int) (videoFrame.getW() * 1.0f / scale);
        lp.width = videoW;
        idVideoRy.setLayoutParams(lp);
        ImageLoader.getInstance().showImageNoplace(V1_2_VideoPreviewActivity.this, bgUrl, idPrvBg);


        RelativeLayout.LayoutParams lyCoverParams = (RelativeLayout.LayoutParams) lyCover.getLayoutParams();
        lyCoverParams.addRule(RelativeLayout.BELOW, R.id.id_ly_edit_content);// 子控件相对于控件：imageViewId在其的下面


        //在图片的上方
        RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) idPrvBgRy.getLayoutParams();
        layoutParams1.addRule(RelativeLayout.BELOW, R.id.id_ly_cover);// 子控件相对于控件：imageViewId在其的下面

        // idPrvBgRy.setLayoutParams(layoutParams1);
        editContent.setVisibility(View.GONE);
        idLyuserMake.setVisibility(View.VISIBLE);
        tvSaveShare.setVisibility(View.GONE);
        tvSaveToLocal.setVisibility(View.VISIBLE);
    }


    /*没有背景*/
    @Override
    protected void cleanBg() {
        isCleanTopMargin = 0;
        idPrvBg.setImageResource(0);
        int videoH = (int) videoBean.getH();
        int[] whd = UIUtils.WHD();
        int visableW = whd[0];
        float scale = (float) (videoBean.getW() * 1.0f / visableW);
        videoH = (int) (videoH * 1.0f / scale);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) idVideoRy.getLayoutParams();
        lp.leftMargin = 0;
        lp.topMargin = 0;
        lp.bottomMargin = 0;
        lp.width = UIUtils.WH()[0];
        lp.height = videoH;


        RelativeLayout.LayoutParams lyCoverParams = (RelativeLayout.LayoutParams) lyCover.getLayoutParams();
        lyCoverParams.addRule(RelativeLayout.BELOW, R.id.id_ly_edit_content);// 子控件相对于控件：imageViewId在其的下面

        //在播放器下方
        lp.addRule(RelativeLayout.BELOW, R.id.id_ly_cover);// 子控件相对于控件：imageViewId在其的下面
        idVideoRy.setLayoutParams(lp);


        RelativeLayout.LayoutParams imgLp = (RelativeLayout.LayoutParams) idPrvBg.getLayoutParams();
        imgLp.width = FrameLayout.LayoutParams.MATCH_PARENT;
        imgLp.height = FrameLayout.LayoutParams.MATCH_PARENT;
        idPrvBg.setLayoutParams(imgLp);

        editContent.setVisibility(View.GONE);
        idLyuserMake.setVisibility(View.GONE);
        tvSaveShare.setVisibility(View.VISIBLE);
        scrollView.scrollTo(0, 0);
    }


    public void showBgDialog() {
        Bundle bundle = new Bundle();
        bundle.putString(AppConst.DOCID, videoPreviewBean.getId() + "");
        bundle.putString(WorkPlatform.TYPE, subType);
        Intent intent = new Intent(V1_2_VideoPreviewActivity.this, VideobgDialgActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }


    /**
     * 去水印状态
     */

    @Override
    public void waterStatus() {
        if (videoPreviewBean == null) return;
        switch (videoPreviewBean.getWatermark()) {
            case 1:
                //已付款
                switch (videoPreviewBean.getWatermarkPay()) {
                    case 1:
                        //有水印 重新发起去水印
                        tvProductTag.setEnabled(true);
                        tvProductTag.setText("去水印");
                        //mPresenter.removeWatermark(videoPreviewBean.getId() + "");
                        break;
                    case 0:
                        tvProductTag.setEnabled(true);
                        tvProductTag.setText("¥" + String.format("%.2f", videoPreviewBean.getWatermarkFee() * 0.01) + getResources().getString(R.string.gotowaterprice));
                        break;
                }
                break;
            case 0:
                tvProductTag.setText("已去水印");
                tvProductTag.setBackgroundResource(R.drawable.shape_un_tag_bg);
                tvProductTag.setTextColor(UIUtils.getColor(R.color.app_smile_text_color));
                tvProductTag.setEnabled(false);
                ryRecommended.setVisibility(View.GONE);

                if (getUserMakeTag().equals(UserMakeTag.REMOVEWATER)) {
                    edTvbg.setTextColor(UIUtils.getColor(R.color.tab_color_false));

                    imageViewbg.setAlpha((float) 0.5);
                    editBg.setEnabled(false);

                    tv_cover_settag.setTextColor(UIUtils.getColor(R.color.app_smile_text_color));
                    //不许点击封面
                    lyCover.setEnabled(false);
                    id_ig_more.setVisibility(View.GONE);
                    //id_tv_cover_tag.setTextColor(UIUtils.getColor(R.color.app_smile_text_color));
                    ig_video_rv.setAlpha((float) 0.5); //注意：透明度取值范围是0~125，0表示完全透明，然后一直递增
                }

                break;
        }

    }


    @Override
    protected void initTitle() {
        super.initTitle();
        //getToolBarView().setVisibility(View.GONE);

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void dataEvent(UserMakeTag userMakeTag) {
        setUserMakeTag(userMakeTag);
        if (userMakeTag.equals(UserMakeTag.SETCOVER) || userMakeTag.equals(UserMakeTag.SETBG)) {
            showProgressDialogWithText("");
            // onPause();
            mPresenter.loadDocPreview(videoPreviewBean.getId() + "");
        } else if (userMakeTag.equals(UserMakeTag.REMOVEWATER)) {
            tvProductTag.setText("去水印");
            videoPreviewBean.setWatermarkPay(1);
            videoPreviewBean.setWatermark(1);
            showProgressDialogWithText("正在努力去水印");
            mPresenter.removeWatermark(videoPreviewBean.getId() + "");
        }
    }


    /**
     * 从不同的界面返回 执行不同的操作
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //选择视频回调
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    String videoUrl = null;
                    for (LocalMedia media : selectList) {
                        Log.i("图片-----》", media.getPath());
                        videoUrl = media.getPath();
                    }
                    Intent intent = new Intent(V1_2_VideoPreviewActivity.this, VideoCoverActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(AppConst.VIDEOURL, videoUrl);
                    bundle.putDouble(AppConst.VIDEOW, 1280);
                    bundle.putDouble(AppConst.VIDEOH, 800);
                    bundle.putBoolean(AppConst.ISLOCALHOSTVIDEO, true);
                    //ClipVideoBean clipVideoBean= (ClipVideoBean) bundle.getSerializable("videoBean");
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 8000);
                    // openActivity(CutVideoActivity.class, bundle);
                    break;

            }
        }

    }


    protected void gotoSelectType() {
        int chooseMode = PictureMimeType.ofVideo();
        // 进入相册 以下是例子：不需要的api可以不写
        PictureSelector.create(V1_2_VideoPreviewActivity.this)
                .openGallery(chooseMode)// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                .maxSelectNum(1)// 最大图片选择数量
                .setOnSelcterVideoFilter(new PictureSelectionConfig.OnSelectClickListner() {

                    @Override
                    public boolean ishasFilter(String url, Activity activity) {
                        if (url != null) {
                            if (EditPlayVideoFrames.getVideoEncodeWithPath(url)) {
                                String duration = UIUtils.videoWHDA(url)[2];
                                //int durationCount = Integer.valueOf(duration);
                                int durationCount = (int) Double.parseDouble(duration);
                                if (durationCount < 1) {
                                    // showUpdateWorkDialog(V1_2_VideoPreviewActivity.class, false, true, false);
                                    return false;
                                }
                                return durationCount <= 180;
                            } else {
                                // showUpdateWorkDialog(activity, true, false, false);
                                return false;
                            }
                            // L_.e(videoEncodeWithPath);
                        }
                        return false;
                    }
                })
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .isCamera(false)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                .isGif(false)// 是否显示gif图片
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .circleDimmedLayer(false)// 是否圆形裁剪
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .openClickSound(false)// 是否开启点击声音
                //.selectionMedia(false)// 是否传入已选图片
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }


    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("p4-作品预览页"); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息。"SplashScreen"为页面名称，可自定义
        MobclickAgent.onPause(this);
    }


}
